package com.javaxiaobear.module.tool.gen.mapper;

import static com.javaxiaobear.module.tool.gen.domain.table.GenTableColumnTableDef.GEN_TABLE_COLUMN;

import com.javaxiaobear.module.tool.gen.domain.GenTableColumn;
import com.mybatisflex.core.BaseMapper;
import com.mybatisflex.core.query.QueryWrapper;
import java.util.Arrays;
import java.util.List;
import org.apache.ibatis.annotations.Select;

/**
 * 业务字段 数据层
 *
 * @author javaxiaobear
 */
public interface GenTableColumnMapper extends BaseMapper<GenTableColumn> {
  /**
   * 根据表名称查询列信息
   *
   * @param tableName 表名称
   * @return 列信息
   */
  @Select(
      "select column_name, (case when (is_nullable = 'no' && column_key != 'PRI') then '1' else '0' end) as is_required, (case when column_key = 'PRI' then '1' else '0' end) as is_pk, ordinal_position as sort, column_comment, (case when extra = 'auto_increment' then '1' else '0' end) as is_increment, column_type\n"
          + "from information_schema.columns where table_schema = (select database()) and table_name = (#{tableName})\n"
          + "order by ordinal_position")
  List<GenTableColumn> selectDbTableColumnsByName(String tableName);

  /**
   * 查询业务字段列表
   *
   * @param tableId 业务字段编号
   * @return 业务字段集合
   */
  default List<GenTableColumn> selectGenTableColumnListByTableId(Long tableId) {
    QueryWrapper queryWrapper =
        QueryWrapper.create()
            .where(GEN_TABLE_COLUMN.TABLE_ID.eq(tableId))
            .orderBy(GenTableColumn::getOrderByColumn, true);
    return selectListByQuery(queryWrapper);
  }

  /**
   * 新增业务字段
   *
   * @param genTableColumn 业务字段信息
   * @return 结果
   */
  default int insertGenTableColumn(GenTableColumn genTableColumn) {
    return insert(genTableColumn);
  }

  /**
   * 修改业务字段
   *
   * @param genTableColumn 业务字段信息
   * @return 结果
   */
  default int updateGenTableColumn(GenTableColumn genTableColumn) {
    return update(genTableColumn);
  }

  /**
   * 删除业务字段
   *
   * @param genTableColumns 列数据
   * @return 结果
   */
  default int deleteGenTableColumns(List<GenTableColumn> genTableColumns) {
    if (genTableColumns == null || genTableColumns.isEmpty()) {
      return 0;
    }

    List<Long> ids =
        genTableColumns.stream().map(GenTableColumn::getColumnId).filter(id -> id != null).toList();

    return deleteBatchByIds(ids);
  }

  /**
   * 批量删除业务字段
   *
   * @param ids 需要删除的数据ID
   * @return 结果
   */
  default int deleteGenTableColumnByIds(Long[] ids) {
    if (ids == null || ids.length == 0) {
      return 0;
    }

    QueryWrapper queryWrapper =
        QueryWrapper.create().where(GEN_TABLE_COLUMN.TABLE_ID.in(Arrays.asList(ids)));
    return deleteByQuery(queryWrapper);
  }
}
